#!/usr/bin/python
# -*- coding: utf-8 -*-

import urllib, urllib2, re, xbmcplugin, xbmcgui, threading
from sgmllib import SGMLParser                
def get_params():
        param=[]
        paramstring=sys.argv[2]
        if len(paramstring)>=2:
                params=sys.argv[2]
                cleanedparams=params.replace('?','')
                if (params[len(params)-1]=='/'):
                        params=params[0:len(params)-2]
                pairsofparams=cleanedparams.split('&')
                param={}
                for i in range(len(pairsofparams)):
                        splitparams={}
                        splitparams=pairsofparams[i].split('=')
                        if (len(splitparams))==2:
                                param[splitparams[0]]=splitparams[1]
                                
        return param




def addLink(name,artist,url,iconimage):
        ok=True
        liz=xbmcgui.ListItem(name, iconImage="DefaultMusic.png", thumbnailImage=iconimage)
        liz.setInfo( type="Music", infoLabels={ "Title": name, "Album": artist } )
        ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
        return ok
####################################################################################
# Sveriges Radio plugin for XBMC
####################################################################################
class RadioChannel:
    
    def __init__(self, name = '', url = '', info = ''):
        self.__name = name
        self.__url = url
        self.__info = info
    
    def setName(self, name):
        self.__name = name
    
    def getName(self):
        return self.__name
    
    def setURL(self, url):
        self.__url = url
    
    def getURL(self):
        return self.__url
    
    def setInfo(self, info):
        self.__info = info
    
    def getInfo(self):
        return self.__info
    
     

class BaseHTMLProcessor(SGMLParser):
    def reset(self):                      
        # extend (called by SGMLParser.__init__)
        self.pieces = ''
        SGMLParser.reset(self)
        self.insideRightNow = False
        self.insideChannel = False
        self.channelInfo = []
        self.channels = {}     

    def start_td(self, attributes):
        if len(attributes[0]) > 1:
            if attributes[0][1] == 'rightNowColumn':
                self.insideRightNow = True
                self.pieces = ''
            elif attributes[0][1] == 'channelColumn':
                self.insideChannel = True
                self.pieces = ''
       
    def end_td(self):
        if self.insideRightNow == True:
            self.pieces = self.pieces.replace('\r\n', '')
            self.pieces = re.sub("\s+" , " ", self.pieces)
            self.pieces = self.pieces.strip()
            self.channelInfo.append(self.pieces)
            #Use this as a key
            key = self.channelInfo[0].split('-')[0].strip()
            key = key.lower()
            key = key.replace('sr ', '', 1)
            key = key.replace('á', 'a')
            #If we are at the P4 channel, replace the swedish letters åäö with aao
            if (len(key) > 3) and (key[:3] == 'p4 '):
                key = key.replace('å', 'a')
                key = key.replace('ä', 'a')
                key = key.replace('ö', 'o')
                key = key.replace('Ö', 'o')#Why isn't Ö lowered with lower()? 
                key = key[3:]
            
            self.channels[key] = self.channelInfo 
            self.channelInfo = []
            self.insideRightNow = False
        elif self.insideChannel == True:
            self.pieces = self.pieces.replace('\r\n', '')
            self.pieces = re.sub("\s+" , " ", self.pieces)
            self.pieces = self.pieces.strip()
            self.channelInfo.append(self.pieces)
            self.insideChannel = False           

    def handle_entityref(self, ref):
        self.handle_data(ref)       

    def handle_data(self, text):          
        if((self.insideChannel == True) or (self.insideRightNow == True)):
            self.pieces = self.pieces + text   

    def get_channels(self):
        return self.channels 

class StreamingURLSRParser(SGMLParser): 
    def reset(self):                      
        # extend (called by SGMLParser.__init__)
        self.pieces = ''
        SGMLParser.reset(self)
        self.collect = False
        self.insideLink = False
        self.insideStrong = False
        self.channelInfo = []
        self.channels = {}   

    def start_a(self, attributes):
        #Only interested in high quality streams...
	self.insideLink = True
        if self.collect == True:
            #new Radio channel object
            radioCh = RadioChannel()
            
            if (self.pieces.find('bredband') != -1):
                self.pieces = self.pieces.strip()
                linePieces = self.pieces.splitlines()
                radioCh.setName(linePieces[len(linePieces) - 1][:-10].strip(','))
                self.pieces = ''
                
                if(attributes[0][0] == 'href'):
                    indexOfHigh = attributes[0][1].lower().find('high')
                    if indexOfHigh != -1:
                        if attributes[0][1][0:4] == 'mms:':
                            radioCh.setURL(attributes[0][1])
                            key = radioCh.getName().lower().replace('sr ', '', 1)
                            if key.find('p4 med') != -1:
                                key = key.replace('p4 med ', '')#Fix for P4 med radiosporten.
                            self.channels[key] = radioCh
                
            elif self.pieces.find('Lokala kanaler Windows Media hög kvalitet:') != -1:
                #handle the local station differently. There is no heading for the links...
                if(attributes[0][0] == 'href'):
                    indexOfHigh = attributes[0][1].lower().find('high')
                    if indexOfHigh != -1:
                        if attributes[0][1][0:4] == 'mms:':
                            radioCh.setURL(attributes[0][1])
                            urlPieces = attributes[0][1].split('-')
                            key = urlPieces[len(urlPieces) - 2].lower()
                            self.channels[key] = radioCh
            
    def end_a(self):
	self.insideLink = False

    def start_div(self, attributes):
        try:
            if (attributes[0][0] == 'class') and (attributes[0][1] == 'text11'):
                self.collect = True
        except:
            print 'outch'           

    def end_div(self):
        self.collect = False

    def handle_data(self, text):
    	if (self.collect == True) and (self.insideLink == False):		 
		self.pieces += text

    def get_urls(self):
        return self.channels

class RadioShowInfo(threading.Thread):
    channelInfo = {}
    
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        try:
            webPageHandle = urllib.urlopen('http://www.sr.se/cgi-bin/kanaler/')
            webPageData = webPageHandle.read()
	    webPageHandle.close()
        except(IOError):
            webPageHandle.close()
            print(IOError.message)
        else:
            htmlParser = BaseHTMLProcessor()
            htmlParser.reset()
            htmlParser.feed(webPageData)
            self.channelInfo = htmlParser.get_channels()
            htmlParser.close()            
            
    def getRadioShowInfo(self):
        return self.channelInfo

class StreamURLs(threading.Thread):
    availableWebCasts = {}
    
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        try:
            webPageHandle = urllib.urlopen('http://www.sr.se/sida/artikel.aspx?ProgramId=2321&Artikel=787720')
            webPageData = webPageHandle.read()
            webPageHandle.close()
        except:
            webPageHandle.close()
            print(IOError.message)
        else:
            streamURLParser = StreamingURLSRParser()
            streamURLParser.reset()
            streamURLParser.feed(webPageData)
            self.availableWebCasts = streamURLParser.get_urls()

    def getStreamingURLs(self):
        return self.availableWebCasts

class RadioScraper(object):
    '''

    classdocs

    '''
    __url = None
    __rawData = None
    __availableWebCasts = {}

    def __init__(self):
        '''
        Constructor
        '''    

    def ScrapeData(self):
        #Fetch available radio shows and info
        sUrls = StreamURLs()
        radioShowInfo = RadioShowInfo()
        sUrls.start()
        radioShowInfo.start()    

        sUrls.join()
        self.__availableWebCasts = sUrls.getStreamingURLs()
        
        radioShowInfo.join()        
        channelInfo = radioShowInfo.getRadioShowInfo()

        
        #Add the info to available channels,
        for k in self.__availableWebCasts.keys():
            if k in channelInfo:
                self.__availableWebCasts[k].setInfo(channelInfo[k][1])
                self.__availableWebCasts[k].setName(channelInfo[k][0])
            else:
                self.__availableWebCasts[k].setInfo('N/A')
                #self.__availableWebCasts[k].setName('N/A')

    def GetChannels(self):
	return self.__availableWebCasts


scrape = RadioScraper()                
scrape.ScrapeData()

for k, v in scrape.GetChannels().iteritems():        addLink(v.getName(),v.getInfo(),v.getURL(),'')
		
SORT_METHOD_TITLE = 9
SORT_METHOD_GENRE = 15
SORT_METHOD_ARTIST = 11
SORT_METHOD_ALBUM = 13

xbmcplugin.addSortMethod(int(sys.argv[1]), SORT_METHOD_ALBUM)
xbmcplugin.addSortMethod(int(sys.argv[1]), SORT_METHOD_ARTIST)
xbmcplugin.addSortMethod(int(sys.argv[1]), SORT_METHOD_GENRE)
xbmcplugin.addSortMethod(int(sys.argv[1]), SORT_METHOD_TITLE)

xbmcplugin.endOfDirectory(int(sys.argv[1]))
